package com.onetech.adrewards.free.dialogs;

import java.util.Random;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fedorvlasov.lazylist.ImageLoader;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.activities.SocialShareActivity;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.ResultDTO;
import com.zuzu.dialogs.BaseDialog;



	


public class ShareTwitterDialog extends BaseDialog {
	private Tracker mTracker;
	private SocialShareActivity mContext=null;
	private Twitter mTwitter;
	private TextView mShareText;
	
	
	private ImageView mCover;
	private Button mTweetBtn;
	
	private Button mSignOutBtn;
	private static String shareText;
	
	private ProgressDialog mProgress;
	
	private GetUpdateStatusTask mGetUpdateStatusTask=null;
	private int buttonPressId=-1; 
	
	public ShareTwitterDialog(SocialShareActivity context, String title,String message) {
		super(context, context.getString(R.string.twitter_share_title), TYPE_NO_BUTTON, R.layout.dialog_share_twitter_layout);
		mContext=context;
		shareText = message;

		try {
			
			
			mSignOutBtn = ((Button) findViewById(R.id.btn_logout));
			mSignOutBtn.setOnClickListener(new View.OnClickListener() {			
				@Override
				public void onClick(View arg0) {
//					mTwitter.clearSession();
//					mContext.clearCredential();
//					dismiss();
					
					SharedPreferences.Editor editor = SocialShareActivity.mSharedPref.edit();
					editor.remove(SocialShareActivity.PREF_KEY_TOKEN);
					editor.remove(SocialShareActivity.PREF_KEY_SECRET);

					editor.commit();
					if(SocialShareActivity.mTwitter != null)
					{
						SocialShareActivity.mTwitter.setOAuthAccessToken(null);
						
					}
				
					
					
					dismiss();
					
				}
			});
			
			mShareText =(TextView) findViewById(R.id.twShareText);
			mShareText.setText(shareText);
			
			
			mTweetBtn = ((Button) findViewById(R.id.btnShare));
			
			
			mTweetBtn.setOnClickListener(this);
			
			
		} catch (Exception e) {
			dismiss();
		}
	}
	

	private void GetUpdateStatusTask(){
		if(mGetUpdateStatusTask==null || mGetUpdateStatusTask.getStatus()==Status.FINISHED){
			mGetUpdateStatusTask=new GetUpdateStatusTask();
			mGetUpdateStatusTask.execute();
		}
	}

	private class GetUpdateStatusTask extends AsyncTask<Void, Void, ResultDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			mProgress = new ProgressDialog(mContext);
			mProgress.setMessage(mContext.getString(R.string.socail_sharing_message));
			mProgress.setCancelable(false);
			mProgress.show();
		}
		@Override
		protected ResultDTO doInBackground(Void... params) {
			try {				
				ResultDTO ret = updateStatus(shareText);
				if("-2".equals(ret.getError_code()))
				{
					Random rand = new Random();
				    int randomNum = rand.nextInt((1000 - 1) + 1) + 1;
				    String text = shareText + " ID:" + randomNum;
				    ret = updateStatus(text);
				}
				return ret;
				
			} catch (Exception e) {
				return null;
			}			
		}
		@Override
		protected void onPostExecute(ResultDTO result) {
			super.onPostExecute(result);
			try {
				if(result != null && "0".equals(result.getError_code())){
					
				     mContext.showToast(mContext.getString(R.string.twitter_tweet_success));
				}else {
					 mContext.showToast(mContext.getString(R.string.twitter_tweet_failed));
			}
			} catch (Exception e) {
				
			}
			finally{
				buttonPressId = -1; 
				if(mProgress != null)
				{
					mProgress.dismiss();
				}
			     dismiss();
			}
		}
	}
	
	
	
	private ResultDTO updateStatus(String text)   {
		
		
		
		ResultDTO result = new ResultDTO();
		result.setError_code("-1");
		
		if (text == null || text.trim().equals("")) {
			mContext.showToast(mContext.getString(R.string.social_empty_message));
			return result;
		}
		
		
		String oauthAccessToken = SocialShareActivity.mSharedPref.getString(SocialShareActivity.PREF_KEY_TOKEN, "");
		String oAuthAccessTokenSecret = SocialShareActivity.mSharedPref.getString(SocialShareActivity.PREF_KEY_SECRET, "");
	 
		 AccessToken accessToken = new AccessToken(oauthAccessToken, oAuthAccessTokenSecret);  
		   
		 // つぶやく  
		 Twitter twitter = new TwitterFactory().getInstance();  
		 twitter.setOAuthConsumer(SocialShareActivity.CONSUMER_KEY, SocialShareActivity.CONSUMER_SECRET);  
		 twitter.setOAuthAccessToken(accessToken);  
		 try {  
			 
			  twitter.updateStatus(text ); 
			
			  CommonModel.getInstance().doSocialCoin("8");
			  mContext.updateUser();
			  result.setError_code("0");
			 
		   
		    
		 } catch (TwitterException e) {  
		     //android.util.Log.e("TwitterException", e.toString());  
			 result.setError_code("-2");
		     
		 }  
		 return result;
		 
		
		
		 
		 
		
//		TwitterRequest request 		= new TwitterRequest(mTwitter.getConsumer(), mTwitter.getAccessToken());
//		String updateStatusUrl		= "https://api.twitter.com/1.0/statuses/update.json";
//		List<NameValuePair> params 	= new ArrayList<NameValuePair>(1);
//		
//		params.add(new BasicNameValuePair("status", URLEncoder.encode(shareText, "UTF-8")));
//		
//		
//		request.createRequest("POST", updateStatusUrl, params, new TwitterRequest.RequestListener() {
//			@Override
//			public void onSuccess(String response) {
//				progressDlg.dismiss();
//				mContext.showToast(mContext.getString(R.string.twitter_tweet_success));
//				CommonModel.getInstance().doSocialCoin("8");
//				dismiss();
//				//Debug.i(response);
//			}
//			
//			@Override
//			public void onError(String error) {
//				mContext.showToast(mContext.getString(R.string.twitter_tweet_failed));
//				progressDlg.dismiss();
//			}
//		});
	}
		
	@Override
	public void onClick(View view) {
		int id =view.getId();
		switch (id) {
		case R.id.btnShare:	
				if(buttonPressId == -1)
				{
					buttonPressId = R.id.btnShare;
					GetUpdateStatusTask();
				}
			
			break;
		
		default:
			super.onClick(view);
			break;
		}
	}

	
	
	
	@Override
    public void onStart() {
        super.onStart();
        try {
            mTracker.set(Fields.SCREEN_NAME, mContext.getString(R.string.ShareTwitterDialog));            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
    }
}
